<template>
  <div class="user-manage">
    <!-- 查询区域 -->
    <el-form :model="searchForm" inline label-width="80px">
      <el-form-item label="姓名">
        <el-input v-model="searchForm.name" placeholder="请输入姓名"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 新增按钮 -->
    <el-button type="success" @click="handleAdd">新增用户</el-button>

    <!-- 表格展示数据 -->
    <el-table :data="tableData" border style="width: 100%; margin-top: 15px;" @row-dblclick="handleEdit">
      <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
      <el-table-column prop="phone" label="手机号" align="center"></el-table-column>
      <el-table-column label="密码" align="center">
        <template #default="scope">
          <div class="password-cell">
            <!-- 显示的内容：隐藏时显示***，显示时显示真实密码 -->
            <span v-if="!scope.row.showPwd">*************</span>
            <span v-else>{{ scope.row.password }}</span>

            <!-- 切换按钮 -->
            <el-button
                type="text"
                style="color: black;"
                size="large"
                @click="togglePasswordVisibility(scope.row)"
                :icon=" View"

            ></el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="姓名" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 加载中状态 -->
    <el-loading v-loading="loading" target=".user-manage" text="加载中..."></el-loading>

    <!-- 分页组件 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="searchForm.page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="searchForm.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 15px; text-align: right;">
    </el-pagination>

    <!-- 新增/编辑弹窗 -->
    <el-dialog title="用户信息" v-model="dialogVisible" width="500px">
      <el-form :model="form" label-width="100px" :rules="rules" ref="formRef">
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" :type="form.id ? 'password' : 'password'"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import api from "@/util/api.js";

import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import {View} from "@element-plus/icons-vue";
// 切换密码显示/隐藏状态（针对表格中的每一行）
const togglePasswordVisibility = (row) => {
  // 为当前行添加 showPwd 属性（若不存在则初始化为 false）
  if (row.showPwd === undefined) {
    // 初始化时默认隐藏密码
    row.showPwd = false;
  } else {
    // 已存在则切换状态（显示 ↔ 隐藏）
    row.showPwd = !row.showPwd;
  }
};

// 搜索表单
const searchForm = reactive({
  name: '',
  page: 1,
  pageSize: 10
})

// 表格数据
const tableData = ref([])
// 总条数
const total = ref(0)
// 弹窗显示状态
const dialogVisible = ref(false)
// 加载状态
const loading = ref(false)
// 表单引用
const formRef = ref(null)

// 表单数据（新增/编辑用）
const form = reactive({
  id: '',
  phone: '',
  password: '',
  name: ''
})

// 表单验证规则
const rules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ]
}

// 获取数据列表
const getList = async () => {
  try {
    // 显示加载状态
    loading.value = true

    const res = await api.get('/users/list', {
      params: searchForm
    })

    // 假设后端返回格式：{ code: 200, data: { records: [], total: 0 } }
    if (res && res.code === 200) {
      tableData.value = res.data?.records || []
      total.value = res.data?.total || 0
    } else {
      ElMessage.warning('获取数据格式不正确')
      tableData.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取数据失败：', error)
    ElMessage.error('获取数据失败，请稍后重试')
    tableData.value = []
    total.value = 0
  } finally {
    // 隐藏加载状态
    loading.value = false
  }
}

// 确保组件挂载后再加载数据
onMounted(() => {
  getList()
})

// 搜索
const handleSearch = () => {
  searchForm.page = 1
  getList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.page = 1
  getList()
}

// 新增
const handleAdd = () => {
  form.id = ''
  form.phone = ''
  form.password = ''
  form.name = ''
  dialogVisible.value = true
  // 重置表单验证
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 编辑（双击行或点击编辑按钮）
const handleEdit = (row) => {
  form.id = row.id
  form.phone = row.phone
  form.password = row.password
  form.name = row.name
  dialogVisible.value = true
  // 重置表单验证
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 保存（新增/编辑）
const handleSave = async () => {
  // 表单验证
  if (!formRef.value) return
  await formRef.value.validate().catch(() => {
    return Promise.reject(new Error('表单验证失败'))
  })

  try {
    let res
    if (form.id) {
      // 编辑操作
      res = await api.put('/users/update', form)
    } else {
      // 新增操作
      res = await api.post('/users/save', form)
    }

    if (res && res.code === 200) {
      dialogVisible.value = false
      ElMessage.success(form.id ? '修改成功' : '新增成功')
      getList() // 重新加载列表
    } else {
      ElMessage.error(res.data?.msg || '操作失败')
    }
  } catch (error) {
    console.error('操作失败：', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    // 统一使用api对象，保持一致性
    const res = await api.delete(`/users/delete`,{data: [row.id]})

    if (res && res.code === 200) {
      ElMessage.success('删除成功')
      getList()
    } else {
      ElMessage.error(res.data?.msg || '删除失败')
    }
  } catch (error) {
    // 取消操作不提示错误
    if (error.name !== 'CanceledError') {
      console.error('删除失败：', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }
}

// 每页条数改变
const handleSizeChange = (val) => {
  searchForm.pageSize = val
  searchForm.page = 1
  getList()
}

// 当前页改变
const handleCurrentChange = (val) => {
  searchForm.page = val
  getList()
}
</script>

<style scoped>
.user-manage {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 40px);
}
.dialog-footer {
  text-align: right;
}
</style>
